package beanstao.util.j2ee.tidy;

import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class TidyHelper
{
	@SuppressWarnings("unchecked")
	public static String tidyKeyValue(String key, String value)
	{
		boolean flag = TidySetting.ME().getTidyMap().containsKey(key);
		if (flag)
		{
			@SuppressWarnings("rawtypes")
			ITidy tidyClass = TidySetting.ME().getTidyMap().get(key);
			if ((tidyClass == null) || (tidyClass.tidy(key, value) == null))
				return value;
			Object result = tidyClass.tidy(key, value).getRight();
			if (null == result)
				return value;
			return result.toString();
			// if ((tidyClass == null) || (tidyClass.tidy(key, value) == null) || (tidyClass.tidy(key, value).getRight() ==
			// null))
			// return value;
			// return tidyClass.tidy(key, value).getRight().toString();
		}
		return value;
	}

	public static String tidyJson(String jsonSrc)
	{
		if ('{' == jsonSrc.trim().charAt(0))
		{
			JSONObject jsonObject = JSONObject.fromObject(jsonSrc);
			if (jsonObject.get("records") != null)
			{
				JSONArray jsonArray = JSONArray.fromObject(jsonObject.get("records"));
				jsonObject.put("records", forJSONArray(jsonArray));
			}
			return forJSONObject(jsonObject).toString();
		}
		else if ('[' == jsonSrc.trim().charAt(0))
		{
			JSONArray jsonArray = JSONArray.fromObject(jsonSrc.trim());
			return forJSONArray(jsonArray).toString();
		}
		else
			return jsonSrc;
	}

	private static JSONArray forJSONArray(JSONArray jsonArray)
	{
		for (Object object : jsonArray)
			toJsonProcessMethod(object);
		return jsonArray;
	}

	@SuppressWarnings("unchecked")
	private static <T> JSONObject forJSONObject(JSONObject jsonObject)
	{
		for (Object jo : jsonObject.entrySet())
		{
			Map.Entry<String, Object> entry = (Map.Entry<String, Object>) jo;
			String key = entry.getKey();
			boolean flag = TidySetting.ME().getTidyMap().containsKey(key.toLowerCase());
			if (flag)
			{
				T str = (T) TidySetting.ME().getTidyMap().get(key).tidy(key, entry.getValue().toString()).getRight();
				entry.setValue(str);
			}
		}
		return jsonObject;
	}

	private static void toJsonProcessMethod(Object object)
	{
		if (object instanceof JSONArray)
			forJSONArray((JSONArray) object);
		if (object instanceof JSONObject)
			forJSONObject((JSONObject) object);
	}
}
